#include "cMan.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#ifndef DEF_CIRC_BUF_SIZE
#define DEF_CIRC_BUF_SIZE 256
#endif

#ifndef DEF_AUDIO_IN_PATH
#define DEF_AUDIO_IN_PATH "/dev/dsp"
#endif

const char *confPath = {"./"};
const char *confFile = {"eden.conf"};

typedef enum {INT,STRING,ERROR_TYPE} TYPE;

typedef struct
{
	char* keyName;
	TYPE keyType;
	keyValue_u value;
} keyStruct_s;

static keyStruct_s KEYS[NUM_OF_KEYS+1] = {
	{"CIRC_BUFFER_SIZE", INT, {.num=DEF_CIRC_BUF_SIZE}},
	{"AUDIO_INPUT_PATH", STRING, {.str=DEF_AUDIO_IN_PATH}},
	{"ERROR!!!!", ERROR_TYPE, {.flag=FALSE}} /* must be last */
};

BOOL initilized = FALSE;

void initializeCMan(int numOfArguments, char* arguments[])
{ 
    FILE* conf = NULL;
    char key[50];
    char value[50];
    int tokens = 0;
    char *absolutePath = NULL;
    KEY_MAPPING keysIndex = 0;
    
    if (initilized != FALSE )
    	return;
    initilized = TRUE;
    absolutePath = (char*) malloc ((sizeof(confPath)+sizeof(confFile))*sizeof(char));
    
    sprintf(absolutePath,"%s%s",confPath, confFile);
    if ((conf = fopen(absolutePath,"r"))!=NULL)
    {
    	BOOL found = FALSE;
        while ((tokens = fscanf(conf,"%s%*[ \t]%s%*[ \t]",key ,(char*) &value))!=EOF)
        {
            if(tokens == 2)
            {
            	found = FALSE;
            	for (keysIndex=KEYS_BEGIN; !found && keysIndex<NUM_OF_KEYS;++keysIndex)
            	{
            		if (strcmp(KEYS[keysIndex].keyName,key)==0)
            		{
            			found=TRUE;
            		}
            	}
            }
            if (found == TRUE)
            {
            	switch (KEYS[keysIndex].keyType)
            	{
            	case INT:
            		KEYS[keysIndex].value.num = atoi(value);
            		break;
            	case STRING:
            		KEYS[keysIndex].value.str = strdup(value);
            		break;
            	case ERROR_TYPE:
            		break;
            	}
            }
        }
        fclose(conf);
    }
    free(absolutePath);
}

keyValue_u getFromCMan(KEY_MAPPING key)
{
    if (initilized != TRUE )
    	return KEYS[NUM_OF_KEYS].value;
    
	if ( key==KEYS_BEGIN || key==NUM_OF_KEYS)
		return KEYS[NUM_OF_KEYS].value;
	
	return KEYS[key].value;
}

void destroyCMan()
{
	KEY_MAPPING keysIndex;

    if (initilized != TRUE )
    	return;
	
	for (keysIndex=KEYS_BEGIN; keysIndex<NUM_OF_KEYS;++keysIndex)
	{
		if (KEYS[keysIndex].keyType == STRING)
		{
			free(KEYS[keysIndex].value.str);
		}
	}
	
	initilized = FALSE;
}
